/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package CONTROLLERS;

import BEANS.Account;
import UTIL.DatabaseConnector;
import UTIL.InputValidator;
import UTIL.TableManager;
import VIEW.Main;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.JTextField;

/**
 *
 * @author Belthazod
 */
public class UserController {
    private DatabaseConnector dbConnector;
    private TableManager userTableManager;
    private JTable userTable;
    private JTextField usernameInput;
    private JTextField nameInput;
    private JPasswordField passwordInput;
    private JPasswordField retype;
    private JDialog editAdminDialog;
    private JPasswordField oldAdminPasswordInput;
    private JPasswordField newAdminPasswordInput;
    private JPasswordField newAdminPasswordConfirmInput;
    private JPasswordField oldUserPasswordInput;
    private JPasswordField newUserPasswordInput;
    private JPasswordField newUserPasswordConfirmInput;
    private JPasswordField confirmPassword;
    private JRadioButton admin;
    private JRadioButton user;
    private JLabel username;
    private JLabel userNameLabel;
    private JDialog editUserDialog;
    private JDialog enterPassword;
    private static ArrayList<Account> accountList;
    private JDialog enterPassword2;
    private JLabel userNameLabel2;
    private JPasswordField confirmPassword2;
    
    public UserController(JPasswordField oldUserPasswordInput, 
            JPasswordField newUserPasswordInput, 
            JPasswordField newUserPasswordConfirmInput,
            JDialog editUserDialog, JLabel username){
        dbConnector = DatabaseConnector.getInstance();
        this.oldUserPasswordInput = oldUserPasswordInput;  
        this.newUserPasswordInput = newUserPasswordInput; 
        this.newUserPasswordConfirmInput = newUserPasswordConfirmInput;
        this.username = username;
        this.editUserDialog = editUserDialog;
        
    }
    /**
     * 
     * @param userTable - the <code>JTable</code> containing the list of users and their respective name
     * @param usernameInput - the <code>JTextField</code> containing the username of the new user to be added
     * @param nameInput - the <code>JTextField</code> containing the name of the new user to be added
     * @param passwordInput - the <code>JPasswordField</code> containing the password of the new user to be added
     * @param editAdminDialog - the <code>JDialog</code> that pops out whenever the admin would like to change his/her password
     * @param oldAdminPasswordInput - the <code>JPasswordField</code> containing the old password of the admin which will soon be changed
     * @param newAdminPasswordInput - the <code>JPasswordField</code> containing the new password of the admin to be used
     * @param newAdminPasswordConfirmInput - the <code>JPasswordField</code> containing and confirming the new password of the administrator
     */
    public UserController(JTable userTable, JTextField usernameInput,JTextField nameInput, JPasswordField passwordInput, 
            JPasswordField retype, JDialog editAdminDialog, JPasswordField oldAdminPasswordInput, JPasswordField newAdminPasswordInput, 
            JPasswordField newAdminPasswordConfirmInput, JRadioButton admin, JRadioButton user, JLabel userNameLabel, 
            JPasswordField confirmPassword, JDialog enterPassword, JLabel userNameLabel2, JPasswordField confirmPassword2, JDialog enterPassword2){
        dbConnector = DatabaseConnector.getInstance();
        this.userNameLabel2 = userNameLabel2;
        this.confirmPassword2 = confirmPassword2;
        this.enterPassword2 = enterPassword2;
        this.userTable = userTable;
        this.usernameInput = usernameInput;
        this.nameInput = nameInput;
        this.passwordInput = passwordInput;
        this.retype = retype;
        this.editAdminDialog = editAdminDialog;
        this.oldAdminPasswordInput = oldAdminPasswordInput;
        this.newAdminPasswordInput = newAdminPasswordInput;
        this.newAdminPasswordConfirmInput = newAdminPasswordConfirmInput;
        this.admin = admin;
        this.user = user;        
        this.userNameLabel = userNameLabel;
        this.confirmPassword = confirmPassword;
        this.enterPassword = enterPassword;
        userTableManager = new TableManager(userTable);
        accountList = new ArrayList<Account>();
        
    }
    
    public void addUser(){
        String password = new String(passwordInput.getPassword());
        String retypePW = new String(retype.getPassword());
        try{
        
        JTextField[] inputs = {usernameInput, nameInput, passwordInput, retype};
        
        if(InputValidator.checkInput(usernameInput.getText(), "Username cannot be empty")
            & InputValidator.checkInput(nameInput.getText(), "Name cannot be empty")    
            & InputValidator.checkInput(new String(passwordInput.getPassword()), "Password cannot be empty")){
            if(password.equals(retypePW)){
            dbConnector.insert("INSERT INTO users (username, name, password, type) "
                    + "VALUES(?,?,?,?)", 
                    new String[]{usernameInput.getText(), nameInput.getText(),
                        new String(passwordInput.getPassword()), "admin"});
            JOptionPane op = new JOptionPane(nameInput.getText() + " has successfully been added to list of users.",JOptionPane.INFORMATION_MESSAGE);
                JDialog dialog = op.createDialog("Add User");
                dialog.setAlwaysOnTop(true);
                dialog.setModal(true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
           // JOptionPane.showMessageDialog(null, nameInput.getText() + " has been added to list of users.", "Success", JOptionPane.INFORMATION_MESSAGE);
            InputValidator.clearInput(inputs);
            updateUsersTable();
        }else{
                JOptionPane op = new JOptionPane("Sorry the password you entered did not match. Please try again.",JOptionPane.ERROR_MESSAGE);
                JDialog dialog = op.createDialog("Input Error");
                dialog.setAlwaysOnTop(true);
                dialog.setModal(true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
                //JOptionPane.showMessageDialog(null, "Sorry. Your passwords do not match, please check and try again.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        dbConnector.closeConnection();
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
            JOptionPane op = new JOptionPane("User already exist.",JOptionPane.ERROR_MESSAGE);
                JDialog dialog = op.createDialog("Database Error");
                dialog.setAlwaysOnTop(true);
                dialog.setModal(true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
            //JOptionPane.showMessageDialog(null,"User already exist.","Database error",JOptionPane.ERROR_MESSAGE);
        }
        
    }
    /**
     * Queries from the database the list of users and displays their name and username on the User <code>JTable</code>
     */
    
    public void addNewUser(){
        String password = new String(passwordInput.getPassword());
        String retypePW = new String(retype.getPassword());
        try{
        
        JTextField[] inputs = {usernameInput, nameInput, passwordInput, retype};
        
        if(InputValidator.checkInput(usernameInput.getText(), "Username cannot be empty")
            & InputValidator.checkInput(nameInput.getText(), "Name cannot be empty")    
            & InputValidator.checkInput(new String(passwordInput.getPassword()), "Password cannot be empty")){
            if(password.equals(retypePW)){
                if(admin.isSelected()){
            dbConnector.insert("INSERT INTO users (username, name, password, type, question, answer) "
                    + "VALUES(?,?,?,?,?,?)", 
                    new String[]{usernameInput.getText(), nameInput.getText(),
                        new String(passwordInput.getPassword()), "admin", "N/A", "N/A"});
            JOptionPane op = new JOptionPane(nameInput.getText() + " has successfully been added to list of users.",JOptionPane.INFORMATION_MESSAGE);
                JDialog dialog = op.createDialog("Add User");
                dialog.setAlwaysOnTop(true);
                dialog.setModal(true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
           // JOptionPane.showMessageDialog(null, nameInput.getText() + " has been added to list of users.", "Success", JOptionPane.INFORMATION_MESSAGE);
            InputValidator.clearInput(inputs);
            updateUsersTable();
            }else if(user.isSelected()){
            dbConnector.insert("INSERT INTO users (username, name, password, type, question, answer) "
                    + "VALUES(?,?,?,?,?,?)", 
                    new String[]{usernameInput.getText(), nameInput.getText(),
                        new String(passwordInput.getPassword()), "user", "N/A", "N/A"});
            JOptionPane op = new JOptionPane(nameInput.getText() + " has successfully been added to list of users.",JOptionPane.INFORMATION_MESSAGE);
                JDialog dialog = op.createDialog("Add User");
                dialog.setAlwaysOnTop(true);
                dialog.setModal(true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
           // JOptionPane.showMessageDialog(null, nameInput.getText() + " has been added to list of users.", "Success", JOptionPane.INFORMATION_MESSAGE);
            InputValidator.clearInput(inputs);
            updateUsersTable();
            }else{
                JOptionPane.showMessageDialog(null, "Please select the type of user you would like to add.", "Add New User", JOptionPane.ERROR_MESSAGE);
            }
                
        }else{
                JOptionPane op = new JOptionPane("Sorry the password you entered did not match. Please try again.",JOptionPane.ERROR_MESSAGE);
                JDialog dialog = op.createDialog("Input Error");
                dialog.setAlwaysOnTop(true);
                dialog.setModal(true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
                //JOptionPane.showMessageDialog(null, "Sorry. Your passwords do not match, please check and try again.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        dbConnector.closeConnection();
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
            JOptionPane op = new JOptionPane("User already exist.",JOptionPane.ERROR_MESSAGE);
                JDialog dialog = op.createDialog("Database Error");
                dialog.setAlwaysOnTop(true);
                dialog.setModal(true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
            //JOptionPane.showMessageDialog(null,"User already exist.","Database error",JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public void updateUsersTable(){
        try{ 
            userTableManager.importDBContents(dbConnector.query("SELECT username, name FROM users ORDER BY 2")); 
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
            JOptionPane op = new JOptionPane("Failed to update Users Table.",JOptionPane.ERROR_MESSAGE);
                JDialog dialog = op.createDialog("Database Error");
                dialog.setAlwaysOnTop(true);
                dialog.setModal(true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
           // JOptionPane.showMessageDialog(null, "Failed to update Users' table", "Database error.", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    public void getUsersList(){
        try{
            ResultSet rs = dbConnector.query("SELECT username, name, password FROM users");
            while(rs.next()){
                String username = rs.getString(1);
                String name = rs.getString(2);
                String password = rs.getString(3);
                
                accountList.add(new Account(username, password, name));
            }
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
            
        }
    }
    
    /**
     * deletes the selected user in the User <code>JTable</code>
     */
    public void deleteSelectedUser(){
        String username = "";        
        try{        
            username = userTableManager.getIDFromTable(userTableManager.getSelectedRow());
            int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete " + username + " from the Users List?","Warning!" ,JOptionPane.YES_NO_OPTION);
            
            if(result == 0){
                userNameLabel2.setText(userNameLabel.getText());
                enterPassword2.setVisible(true);          
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void deleteConfirmation(){
        String username = "";
        try{
        username = userTableManager.getIDFromTable(userTableManager.getSelectedRow());           
        ResultSet rs = dbConnector.query("SELECT password FROM users WHERE username = '" + userNameLabel2.getText() + "';");
        rs.next();
        String pass = rs.getString(1);
        String pas = new String(confirmPassword2.getPassword());
        System.out.println(pass);
        System.out.println(pas);
        if(pas.equals(pass)){
            dbConnector.delete("DELETE FROM users WHERE username = ?", username);
                updateUsersTable();
                JOptionPane op = new JOptionPane(username + " has successfully been deleted from user list.",JOptionPane.INFORMATION_MESSAGE);
                JDialog dialog = op.createDialog("Delete User");
                dialog.setAlwaysOnTop(true);
                dialog.setModal(true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setVisible(true);
                //JOptionPane.showMessageDialog(null,  username + " deleted from user list.", "Success", JOptionPane.INFORMATION_MESSAGE); 
                enterPassword2.dispose();
        }else{
            JOptionPane.showMessageDialog(null, "The password you have entered is incorrect.", "Wrong Password",JOptionPane.ERROR_MESSAGE);
        }
        }catch(SQLException sqle){
            sqle.printStackTrace();
        }
    }
    
    public void openEditAdminDialog(){
        editAdminDialog.setVisible(true);
    }
    
    public void changeAdminPassword(){
        String oldPassword = new String(oldAdminPasswordInput.getPassword());
        String newPassword = new String(newAdminPasswordInput.getPassword());
        String newPasswordConfirm = new String(newAdminPasswordConfirmInput.getPassword());
        String user = "";
        String name = Main.getNameValue();
        if(Main.getUser().equals("")){
            user = name;
        }else{
            user = Main.getUser();
            Main.setCurrentUser("");
        }
        
        System.out.println(name);
        System.out.println(Main.getUser());
        System.out.println(user);
        if(InputValidator.checkInput(new String(oldAdminPasswordInput.getPassword()), "Old admin password cannot be empty.")
                & InputValidator.checkInput(new String(newAdminPasswordInput.getPassword()), "New admin password cannot be empty.")
                & InputValidator.checkInput(new String(newAdminPasswordConfirmInput.getPassword()), "Confirm admin password cannot be empty.")){
            if(newPassword.equals(newPasswordConfirm)){
                try{
                    ResultSet rs = dbConnector.query("SELECT password FROM users WHERE username = '" + user + "' ");
                    rs.next();
                    System.out.println(rs.getString(1));
                    System.out.println(oldAdminPasswordInput);
                    if(rs.getString(1).equals(oldPassword)){
                        dbConnector.update("UPDATE users SET password = ? where username = ?;", new String[]{ newPassword }, user);
                        JOptionPane op = new JOptionPane("Admin credentials successfully updated.",JOptionPane.INFORMATION_MESSAGE);
                        JDialog dialog = op.createDialog("Change Admin Password");
                        dialog.setAlwaysOnTop(true);
                        dialog.setModal(true);
                        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                        dialog.setVisible(true);
                       // JOptionPane.showMessageDialog(null, "Admin credentials updated.", "Success", JOptionPane.INFORMATION_MESSAGE);
                        editAdminDialog.dispose();
                    }else{
                        dbConnector.update("UPDATE users SET password = ? where username = ?;", new String[]{ newPassword }, " ");
                        JOptionPane op = new JOptionPane("Incorrect admin password.",JOptionPane.ERROR_MESSAGE);
                        JDialog dialog = op.createDialog("Input Error");
                        dialog.setAlwaysOnTop(true);
                        dialog.setModal(true);
                        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                        dialog.setVisible(true);
                       // JOptionPane.showMessageDialog(null, "Incorrect administrator password.", "Input error.", JOptionPane.ERROR_MESSAGE);
                    }
                }catch(SQLException sqlE){
                    sqlE.printStackTrace();
                }
            }else{
                JOptionPane op = new JOptionPane("The Password you entered did not match.",JOptionPane.ERROR_MESSAGE);
                        JDialog dialog = op.createDialog("Input Error");
                        dialog.setAlwaysOnTop(true);
                        dialog.setModal(true);
                        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                        dialog.setVisible(true);
                //JOptionPane.showMessageDialog(null, "Passwords do not match.", "Input Error.", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    public void closeEditDialog(){
        editAdminDialog.dispose();
    }
    
    public void changeUserPassword(){
        String oldPassword = new String(oldUserPasswordInput.getPassword());
        String newPassword = new String(newUserPasswordInput.getPassword());
        String newPasswordConfirm = new String(newUserPasswordConfirmInput.getPassword());
        if(InputValidator.checkInput(new String(oldUserPasswordInput.getPassword()), "Old user password cannot be empty.")
                & InputValidator.checkInput(new String(newUserPasswordInput.getPassword()), "New user password cannot be empty.")
                & InputValidator.checkInput(new String(newUserPasswordConfirmInput.getPassword()), "Confirm user password cannot be empty.")){
            if(newPassword.equals(newPasswordConfirm)){
                try{
                    ResultSet rs = dbConnector.query("SELECT password FROM users WHERE username = ? ", username.getText());
                    rs.next();
                    System.out.println(rs.getString(1));
                    System.out.println(oldPassword);
                    if(rs.getString(1).equals(oldPassword)){
                        rs.close();
                        dbConnector.update("UPDATE users SET password = ? where username = ?", new String[]{ newPassword }, username.getText());
                        JOptionPane.showMessageDialog(null, "User credentials updated.", "Success", JOptionPane.INFORMATION_MESSAGE);
                        editUserDialog.dispose();
                    }else{
                        JOptionPane op = new JOptionPane("Incorrect user password.",JOptionPane.ERROR_MESSAGE);
                        JDialog dialog = op.createDialog("Input Error");
                        dialog.setAlwaysOnTop(true);
                        dialog.setModal(true);
                        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                        dialog.setVisible(true);
                        //JOptionPane.showMessageDialog(null, "Incorrect user password.", "Input error.", JOptionPane.ERROR_MESSAGE);
                    }
                }catch(SQLException sqlE){
                    sqlE.printStackTrace();
                }
            }else{
                JOptionPane op = new JOptionPane("The password you have entered did not match.",JOptionPane.ERROR_MESSAGE);
                        JDialog dialog = op.createDialog("Input Error");
                        dialog.setAlwaysOnTop(true);
                        dialog.setModal(true);
                        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                        dialog.setVisible(true);
               // JOptionPane.showMessageDialog(null, "Passwords do not match.", "Input Error.", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    public void confirmResetPassword(){
        try{
        int newpass = (int) (Math.random()*100000);        
        ResultSet rs = dbConnector.query("SELECT password FROM users WHERE username = '" + userNameLabel.getText() + "';");
        rs.next();
        String pass = rs.getString(1);
        String pas = new String(confirmPassword.getPassword());
        System.out.println(pass);
        System.out.println(pas);
        if(pas.equals(pass)){
            String username = userTableManager.getValueAt(userTableManager.getSelectedRow(), 0);
            dbConnector.update("UPDATE users SET password = ? where username = ?;", new String []{Integer.toString(newpass), username});
            JOptionPane.showMessageDialog(null, newpass, "New password",JOptionPane.INFORMATION_MESSAGE);
            enterPassword.dispose();
        }else{
            JOptionPane.showMessageDialog(null, "The password you have entered is incorrect.", "Wrong Password",JOptionPane.ERROR_MESSAGE);
        }
        }catch(SQLException sqle){
            sqle.printStackTrace();
        }
    }
    
    public void resetPassword(){           
        try{
        String name = userTableManager.getValueAt(userTableManager.getSelectedRow(), 1);
        int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to reset " + name + "'s password?", "Reset Password",JOptionPane.ERROR_MESSAGE);
            if(result == 0){                   
                enterPassword.setVisible(true);                
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    
}
